package com.fingard.dsp.bank.directbank.tenpay01;

import java.io.File;
import java.util.HashMap;

import com.fingard.constant.Format;
import com.fingard.crypto.DigestHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.Base64Helper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 财付通批量代收付
 */
public class TENPAY01BatPayRec extends TENPAY01Base implements IBatPayRec {
	/**
	 * 批量代付交易提交
	 */
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req1988.ownAct, "bat");
			if(actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)){
				retAts.respCode = "0";
				if(actItem == null){
					retAts.respInfo = "未找到账号"+p_req1988.ownAct+"的批量商户配置节点";
				}else{
					retAts.respInfo = "账号"+p_req1988.ownAct+"的证书文件不存在";
				}
				retAts.reqSeqID = p_req1988.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = FailCode.E9981;
				retAts.writeRetToATS();
				return retAts;
			}
			
			XmlTextWriter xmlWriter = new XmlTextWriter();
			xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
			xmlWriter.writeStartElement("root");
			xmlWriter.writeElementString("op_code","1013");
			xmlWriter.writeElementString("op_name", "batch_draw");
			xmlWriter.writeElementString("op_user", actItem.userCode);
			xmlWriter.writeElementString("op_passwd", actItem.userFlag);// 密码明文MD5后
			xmlWriter.writeElementString("op_time",Format.DateTime17Format.format(p_req1988.getPayDateTime()));
			xmlWriter.writeElementString("sp_id", actItem.merchantId);
			xmlWriter.writeElementString("package_id", "");// 包序列ID，未解决
			xmlWriter.writeElementString("total_num", p_req1988.totalNum);
			xmlWriter.writeElementString("total_amt", StringHelper.amountMultiply100(p_req1988.totalAmt));
			xmlWriter.writeElementString("client_ip", actItem.createIP);
			xmlWriter.writeEndElement();
			xmlWriter.writeStartElement("record_set");
			
			while(p_req1988.readRecord()) {
				xmlWriter.writeStartElement("record");
				xmlWriter.writeElementString("serial", p_req1988.readedDetail.askNumber);
				xmlWriter.writeElementString("rec_bankacc", p_req1988.readedDetail.recAct);
				xmlWriter.writeElementString("bank_type", getBankConfig().getMapKeyByValue("bankID", p_req1988.readedDetail.recBankName));
				xmlWriter.writeElementString("rec_name", p_req1988.readedDetail.recName);
				xmlWriter.writeElementString("pay_amt", StringHelper.amountMultiply100(p_req1988.readedDetail.payAmount));
				if (p_req1988.readedDetail.isPrivate.equals("1")) {
					xmlWriter.writeElementString("acc_type", "1");// 对私
				} else {
					xmlWriter.writeElementString("acc_type", "2");// 对公
				}
				xmlWriter.writeElementString("area", p_req1988.readedDetail.getOppProvinceAndCity2()[0]);
				xmlWriter.writeElementString("city", p_req1988.readedDetail.getOppProvinceAndCity2()[1]);
				xmlWriter.writeElementString("subbank_name", p_req1988.readedDetail.recBankLocation);
				xmlWriter.writeElementString("desc", p_req1988.readedDetail.description);
				xmlWriter.writeElementString("recv_mobile", p_req1988.readedDetail.cellPhone);
				xmlWriter.writeEndElement();
			}
			
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();
			
			// 请求报文
			WriteBankLogStep2(xmlWriter.toXmlString());	
						
			// 发送银行
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), getCharset());
			
			// 解析银行返回
			if(tmpStrRet[0].length() == 0){
				String[] respInfo = tmpStrRet[1].split(",");
				String respXml = Base64Helper.getFromBase64(respInfo[0], getCharset());
				
				WriteBankLogLn("银行返回的报文为：" + respXml);
				
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(respXml, tmpSbMsg);
				
				if(tmpBkReader != null){
					retAts.respCode = "0";
					retAts.respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
					retAts.reqSeqID = p_req1988.reqBatchNO;
					retAts.transState = "";
					retAts.payInfoCode = retAts.transState;
				}else{
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			}else if(tmpStrRet[0].equals(ConnState.FAIL)){
				retAts.respCode = "0";
				retAts.respInfo = tmpStrRet[1];
				retAts.reqSeqID = p_req1988.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = tmpStrRet[0];
			}else{
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		}catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.toString();
			e.printStackTrace();
		}
		
		if(retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)){
			retAts.reqSeqID = p_req1988.reqBatchNO;
		}
		
		retAts.writeRetToATS();
		return retAts;
	}

	/**
	 * 财付通批量代付状态查询
	 */
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998)	throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
		retAts.respCode = "";
		
		try{
			ActSetItem actItem = getBankConfig().getActSetItem(p_req1998.ownAct, "");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
				if (actItem == null) {
					throw new Exception("未找到账号" + p_req1998.ownAct + "对应的商户配置节点");
				} else {
					throw new Exception("账号" + p_req1998.ownAct + "对应的证书文件不存在");
				}
			}
			
			
			
			XmlTextWriter xmlWriter = new XmlTextWriter();
			
			xmlWriter.writeElementString("TxCode","");
			xmlWriter.writeElementString("InstitutionID",actItem.merchantId);
			xmlWriter.writeEndElement();
			xmlWriter.writeStartElement("Body");
			xmlWriter.writeElementString("BatchNo",p_req1998.reqBatchNO);
		
			if (p_req1998.reqHeader.commandCode.equals("198801")) {
				xmlWriter.writeElementString("TxType","4534");
			}else {
				xmlWriter.writeElementString("TxType","4534");
			}
			
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();
			
			// 请求报文
			WriteBankLogStep2(xmlWriter.toXmlString());	 
			
			// 发送银行
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), getCharset());
						
		
			if(tmpStrRet[0].length() == 0){
				String[] respInfo = tmpStrRet[1].split(",");
				String respXml = Base64Helper.getFromBase64(respInfo[0], getCharset());
				
				WriteBankLogLn("银行返回的报文为：" + respXml);
				
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(respXml, tmpSbMsg);
				
				if(tmpBkReader != null) {
					String tmpRetCode = tmpBkReader.getFirstText("/Response/Head/Code");
					String tmpRetMsg = tmpBkReader.getFirstText("/Response/Head/Message");
					
	                if (tmpRetCode.equals("2000")){
						retAts.respCode = "0";
						retAts.respInfo = tmpRetMsg;
						retAts.reqSeqID = tmpBkReader.getFirstText("/Response/Body/BatchNo");
						retAts.transState = "";
						retAts.payInfoCode = retAts.transState;
						retAts.writeBeforeDetail();
						
						while(tmpBkReader.read("/Response/Body/Payee")){
							RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
					
							tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("BankAccountNumber");
							tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("BankAccountName");
							tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("Amount");
							tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("Note");
							tmpRetDetail.result = tmpBkReader.readedXElement.getSingleText("Status");
							tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("ResponseCode");
							
							retAts.writeRetDetail(tmpRetDetail);
						}
					}else{
						retAts.respCode = "-1";
						retAts.respInfo = tmpRetMsg;
					}
	                
				}else{
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			}else{
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		}catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.getMessage();
			e.printStackTrace();
		}
		
		if(retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)){
			retAts.reqSeqID = p_req1998.reqBatchNO;
		}
		
		if(retAts.respCode.equals("-1")){
			retAts.writeBeforeDetail();
		}
		
		retAts.writeAfterDetail();
		return retAts;
	}

	/**
	 * 财付通渠道批量代扣
	 */
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188)	throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9188.ownAct, "bat");
			
			if(actItem == null){
				retAts.respCode = "0";
				retAts.respInfo = "未找到账号"+p_req9188.ownAct+"的批量商户配置节点";
				retAts.reqSeqID = p_req9188.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = FailCode.E9981;
				
				retAts.writeRetToATS();
				return retAts;
			}
			
			HashMap<String,String> mapParams = new HashMap<String,String>();
			
			// 协议参数
			mapParams.put("sign_type", "MD5");
			mapParams.put("service_version", "1.1");
			mapParams.put("input_charset", getCharset());
//			mapParams.put("sign", "");
			mapParams.put("sign_key_index", "1");
			mapParams.put("partner", actItem.merchantId);//商户号
			
			//业务参数
			mapParams.put("op_user", actItem.userCode);
			mapParams.put("op_passwd", actItem.userFlag);
			mapParams.put("b_notify_url", "");// 批量通知地址
			mapParams.put("s_notify_url", "");// 单笔扣款成功通知地址
			mapParams.put("batch_id", p_req9188.reqBatchNO);
			mapParams.put("total_count", p_req9188.totalNum);
			mapParams.put("total_fee", StringHelper.amountMultiply100(p_req9188.totalAmt));
			mapParams.put("file_ext", "csv");
//			mapParams.put("file_md5", "");//MD5(file).toUpperCase()
//			mapParams.put("file_body", "");// 不参与签名
			
			File sendFile = createFile(p_req9188.reqBatchNO);
			
			String file_body = getFileBody(p_req9188);
			
			// 向文件写入file_body
			FileHelper.writeFile(sendFile, file_body, getCharset());
			
			byte[] tmpFileDataBytes = DigestHelper.cryptoMD5FromFile(sendFile.getAbsolutePath());
		    String file_md5 = DigestHelper.cryptoMD5RetHexStr(tmpFileDataBytes).toUpperCase();
			mapParams.put("file_md5", file_md5);
			
			String[] retStr = signMessage(mapParams, actItem.saltKey);
			mapParams.put("sign", retStr[1]);
			
			mapParams.put("file_body", file_body);
			
			// 发财付通
			String[] tmpStrRet = sendToBank(sendFile, retStr[0], getCharset());
			
			//解析银行返回响应报文
			if(tmpStrRet[0].length() == 0){
				String retRespStr[] = tmpStrRet[1].split(",");
				
				if (retRespStr[0].equals("0")) {
					retAts.respCode = retRespStr[0];
					retAts.respInfo = retRespStr[1];
					retAts.reqSeqID = p_req9188.reqBatchNO;
					retAts.transState = retRespStr[0];
					retAts.payInfoCode = retRespStr[0];
				}else {
					retAts.respCode = retRespStr[0];
//					retAts.respInfo = retRespStr[2];
					retAts.reqSeqID = p_req9188.reqBatchNO;
					retAts.transState = PaymentState.FAIL_Batch;
					retAts.payInfoCode = retRespStr[0];
				}
			}else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		}catch(Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.toString();
			e.printStackTrace();
		}
		
		if(retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)){
			retAts.reqSeqID = p_req9188.reqBatchNO;
		}
		retAts.writeRetToATS();
		
		return retAts;
	}

	/**
	 * 财付通渠道批量代扣状态查询
	 */
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198)	throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
		retAts.respCode = "";
		
		ActSetItem actItem = getBankConfig().getActSetItem(p_req9198.ownAct, "bat");
		if(actItem == null){			
			retAts.respCode = "-1";
			retAts.respInfo = "未找到账号"+p_req9198.ownAct+"的批量商户配置节点";
			retAts.writeBeforeDetail();
			retAts.writeAfterDetail();
			return retAts;
		}
		
		try{
			HashMap<String,String> mapParams = new HashMap<String,String>();
			
			// 协议参数
			mapParams.put("sign_type", "MD5");
			mapParams.put("service_version", "1.1");
			mapParams.put("input_charset", getCharset());
//			mapParams.put("sign", "");
			mapParams.put("sign_key_index", "1");
			mapParams.put("partner", actItem.merchantId);//商户号
			
			//业务参数
			mapParams.put("op_user", actItem.userCode);
			mapParams.put("op_passwd", actItem.userFlag);
			mapParams.put("result_type", "1");
			mapParams.put("batch_id", p_req9198.reqBatchNO);
			mapParams.put("file_ext", "csv");
			
			String[] retStr = signMessage(mapParams, actItem.saltKey);
			mapParams.put("sign", retStr[2]);
			
			// 发财付通
			String[] tmpStrRet = sendToBank(retStr[1], getCharset());
			
			if(tmpStrRet[0].length() == 0){
				
			}else{
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		}catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.getMessage();
			e.printStackTrace();
		}
		
		if(retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)){
			retAts.reqSeqID = p_req9198.reqBatchNO;
		}
		if(retAts.respCode.equals("-1")){
			retAts.writeBeforeDetail();
		}
		retAts.writeAfterDetail();
		
		return retAts;
	}
}
